package com.navinfo.parkingnavi.fragment;

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.api.directions.v5.models.DirectionsWaypoint;
import com.mapbox.api.directions.v5.models.LegStep;
import com.mapbox.api.directions.v5.models.RouteLeg;
import com.mapbox.api.directions.v5.models.RouteOptions;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.mapbox.geojson.utils.PolylineUtils;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdate;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.services.android.navigation.ui.v5.camera.CameraUpdateMode;
import com.mapbox.services.android.navigation.ui.v5.camera.NavigationCameraUpdate;
import com.mapbox.services.android.navigation.ui.v5.map.NavigationMapboxMap;
import com.navinfo.parkingnavi.Adapter.RoutePoiAutoAdapter;
import com.navinfo.parkingnavi.MainActivity;
import com.navinfo.parkingnavi.R;
import com.navinfo.parkingnavi.dialog.RecommendDialog;
import com.navinfo.parkingnavi.system.SystemConfig;
import com.navinfo.parkingnavi.system.UrlManager;
import com.navinf.parkingnavi.util.FragmentsManager;
import com.navinfo.parkingnavi.util.GsonManager;
import com.navinf.parkingnavi.util.MapManager;
import com.navinfo.parkingnavi.util.NetManager;
import com.navinfo.parkingnavi.util.PositionUtil;
import com.navinfo.parkingnavi.util.StringUtils;
import com.navinfo.parkingnavi.util.SystemUtil;
import com.navinfo.parkingnavi.util.mode.Poi;
import com.navinfo.parkingnavi.widget.content.ContentRecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;
import androidx.recyclerview.widget.LinearLayoutManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/*
 *com.navinfo.parkingnavi.fragment
 *zhjch
 *2020/5/25
 *10:09
 *说明（）
 */
public class RoutePanningFragment extends BaseFragment implements View.OnClickListener, View.OnFocusChangeListener, TextWatcher {
    //起终点和3个途径点
    private Poi mStartPoi, mEndPoi, mAvenuePoi1, mAvenuePoi2, mAvenuePoi3;
    //起终点和3个途径点输入框
    private EditText mStartEdit, mEndEdit, mAvenueEdit1, mAvenueEdit2, mAvenueEdit3;
    //返回按钮,交换按钮
    private View mBackbtn, mChangebtn, mAdd;
    //行驶方式组，poi选择组，方案组
    private Group mGroupType, mGroupSelect, mGroupWays;
    //驾车，骑车，步行
    private TextView mRouteTypeCar, mRouteTypeBike, mRouteTypeWalk;
    //我的位置，地图选点
    private TextView mRouteSelectLoc, mRouteSelectMap;
    // 路径规划及导航的路径点
    private final List<Point> wayPoints = new ArrayList<>();
    // 停车场、外部、总体路径规划的归集类
    private List<Map<String, Object>> routeCollection = new ArrayList<>();
    //导航地图
    private NavigationMapboxMap navigationMapboxMap;

    //行驶方式
    private String type = "car";
    //路径规划网络访问
    private Call mCallRoute;
    //poi网络访问
    private Call mCallPoi;
    //被选中的输入框
    private EditText mSelectEditText;
    //poi联想搜索处理消息
    private final int handler_PoiAuto = 1;
    //联想搜索结果适配器
    private RoutePoiAutoAdapter mAdapter;
    //联想搜索结果展示栏
    private ContentRecyclerView mListView;
    //当前城市code
    private String mCityCode;
    //路径规划方式
    private TextView mRecommend, mNavi;
    //3条规划路径
    private TextView mWay1, mWay2, mWay3;
    //路径规划方式
    private int weighting = 1;
    //楼层
    private String floorId = null;

    private View mClose1, mClose2, mClose3, route_loc;

    public interface OnRoutePanningFragmentListener extends OnBaseFragmentListener {
        void onSelectPoiFromMap();

        void onShowRouteInfo(DirectionsRoute wholeRoute, DirectionsRoute outRoute, List<DirectionsRoute> parkingRouteList);
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == handler_PoiAuto) {
                if (mCallPoi != null && mCallPoi.isExecuted()) {
                    mCallPoi.cancel();
                    mCallPoi = null;
                }
                //如果已知当前要查询的城市
                if (mCityCode != null) {
                    searchPoint(String.valueOf(msg.obj));
                } else {
                    //不知道当前城市，先查询城市code，使用的是当前位置，没有当前位置用地图中心点
                    double lon, lat;
                    Location location = MapManager.getInstance().getMapBox().getLocationComponent().getLastKnownLocation();
                    if (location == null) {
                        LatLng latLng = MapManager.getInstance().getMapBox().getCameraPosition().target;
                        lon = latLng.getLongitude();
                        lat = latLng.getLatitude();
                    } else {
                        lon = location.getLongitude();
                        lat = location.getLatitude();
                    }
                    //获取逆地理编码
                    NetManager.getInstance().getData(UrlManager.getRGeoCodeUrl(lat, lon), new okhttp3.Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            //解析城市编码
                            mCityCode = GsonManager.getInstance().parseCityCode(response.body().string());
                            //查询poi
                            searchPoint(String.valueOf(msg.obj));
                        }
                    });
                }
            }
        }
    };

    /**
     * 查询poi，用的模糊搜索，不限范围
     *
     * @param key
     */
    private void searchPoint(String key) {
        String url = UrlManager.getPoiSearchUrl(key, mCityCode, 1, 20);
        mCallPoi = NetManager.getInstance().getData(url, new okhttp3.Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("jingo", "onFailure: " + e.getMessage());
                mCallPoi = null;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mCallPoi = null;
                if (response != null && response.body() != null) {
                    final ArrayList<Poi> list = GsonManager.getInstance().parsePoiList(response.body().string());

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (list != null && list.size() > 0) {
                                mListView.setVisibility(View.VISIBLE);
                                mAdapter.setData(list);
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        navigationMapboxMap = MapManager.getInstance().getNavigationMapboxMap();
    }

    @Override
    public void onDataChange(Bundle bundle) {

        mGroupType.setVisibility(View.VISIBLE);
        mGroupSelect.setVisibility(View.GONE);
        if (bundle != null) {
            Serializable serializable = bundle.getSerializable(SystemConfig.Bundle_key_my_loc);
            if (serializable != null && serializable instanceof Poi) {
                mStartPoi = (Poi) serializable;
                mStartEdit.setText(mStartPoi.getName_zh());

            }
            serializable = bundle.getSerializable(SystemConfig.Bundle_key_poi);
            if (serializable != null && serializable instanceof Poi) {
                mEndPoi = (Poi) serializable;
                mEndEdit.setText(mEndPoi.getName_zh());

            }
            //点选地图设置poi
            serializable = bundle.getSerializable(SystemConfig.Bundle_select_poi);
            if (serializable != null && serializable instanceof Poi) {
                if (checkPoint((Poi) serializable)) {
                    setPoi((Poi) serializable);
                } else {
                    return;
                }
            }

            if (mEndPoi != null && mStartPoi != null) {
                //请求路径数据
                getRoute();
            }
        }
    }

    /**
     * 获取规划路线
     */
    private void getRoute() {
        mGroupType.setVisibility(View.VISIBLE);
        mGroupSelect.setVisibility(View.GONE);

        navigationMapboxMap.clearMarkers();
        navigationMapboxMap.removeRoute();
        routeCollection.clear();
        if (mCallRoute != null && mCallRoute.isExecuted())
            mCallRoute.cancel();
        List<Poi> pois = new ArrayList<>();
        if (mStartPoi != null) {
            pois.add(mStartPoi);
        } else {
            Toast.makeText(getActivity(), "请设置起点", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mAvenuePoi1 != null) {
            pois.add(mAvenuePoi1);
        }
        if (mAvenuePoi2 != null) {
            pois.add(mAvenuePoi2);
        }
        if (mAvenuePoi3 != null) {
            pois.add(mAvenuePoi3);
        }
        if (mEndPoi != null) {
            pois.add(mEndPoi);
        } else {
            Toast.makeText(getActivity(), "请设置终点", Toast.LENGTH_SHORT).show();
            return;
        }
        mCallRoute = NetManager.getInstance().getData(UrlManager.getRouteLine(pois, type, weighting), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mCallRoute = null;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mCallRoute = null;
//                List<DirectionsRoute> directionsRouteList = new ArrayList<>();
                try {
                    String fileStr = response.body().string();
                    JSONObject jsonObject = new JSONObject(fileStr);
                    List<DirectionsWaypoint> waypointList = new ArrayList<>();
                    if (jsonObject.has("waypoints")) {
                        JSONArray wayPointJsonArray = jsonObject.optJSONArray("waypoints");
                        if (wayPointJsonArray != null && wayPointJsonArray.length() > 0) {
                            for (int i = 0; i < wayPointJsonArray.length(); i++) {
                                JSONObject waypointJsonObject = wayPointJsonArray.getJSONObject(i);
                                DirectionsWaypoint directionsWaypoint = DirectionsWaypoint.builder()
                                        .name(waypointJsonObject.optString("name", "方案" + i))
                                        .rawLocation(new double[]{(double) waypointJsonObject.getJSONArray("location").get(0), (double) waypointJsonObject.getJSONArray("location").get(1)})
                                        .build();
                                waypointList.add(directionsWaypoint);
                            }
                        }
                    }

                    if (jsonObject.has("routes")) {
                        JSONArray routersJsonArray = jsonObject.optJSONArray("routes");
                        if (routersJsonArray != null && routersJsonArray.length() > 0) {
                            RouteOptions options = RouteOptions.builder()
                                    .accessToken("pk.7499d115-b23b-49e5-b71b-76b8da607f1c")
                                    .alternatives(true)
                                    .annotations("congestion,distance")
                                    .approaches(null)
                                    .bannerInstructions(true)
                                    .baseUrl("http://10.130.10.206:8686/mapR/navigation/get/")
                                    .bearings(";")
                                    .continueStraight(true)
                                    .coordinates(wayPoints)
                                    .geometries("polyline6")
                                    .language("zh")
                                    .overview("full")
                                    .profile("driving")
                                    .radiuses(null)
                                    .requestUuid("266d3b7714604863b2a12c6248b6c89c")
                                    .roundaboutExits(true)
                                    .steps(true)
                                    .user("gh")
                                    .voiceInstructions(true)
                                    .voiceUnits("metric")
                                    .build();
                            for (int i = 0; i < routersJsonArray.length(); i++) {
                                JSONObject routerJsonObject = routersJsonArray.getJSONObject(i);
                                DirectionsRoute directionsRoute = DirectionsRoute.fromJson(routerJsonObject.toString());
                                connectRouteLegs(directionsRoute);
                                directionsRoute = directionsRoute.toBuilder().routeOptions(options).build();
                                // 获取室外路径和室内路径geometry
                                JSONArray baseGeometries = null;
                                if (routerJsonObject.has("base_geometries")) {
                                    baseGeometries = routerJsonObject.getJSONArray("base_geometries");
                                }
                                Map<String, Object> map = ((MainActivity) getActivity()).obtainParkingRouteMap(baseGeometries, directionsRoute);
                                routeCollection.add(map);
//                                directionsRouteList.add(DirectionsRoute.builder().routeOptions(options)
//                                        .legs(directionsRoute.legs())
//                                        .distance(directionsRoute.distance())
//                                        .duration(directionsRoute.duration())
//                                        .geometry(directionsRoute.geometry())
//                                        .voiceLanguage("zh")
//                                        .weight(directionsRoute.weight())
//                                        .weightName(directionsRoute.weightName())
//                                        .build());
//                                directionsRouteList.add(directionsRoute);
                            }
                        }
                    }
                    if (routeCollection.size() == 0) {
                        Toast.makeText(getContext(), "路径规划失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    DirectionsRoute route = (DirectionsRoute) routeCollection.get(0).get(MainActivity.KEY_ROUTE_WHOLE);
                    if (route.distance() > 25d) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                MapManager.getInstance().setStartMarker(Point.fromLngLat(mStartPoi.getLon(), mStartPoi.getLat()));
                                MapManager.getInstance().setDestinationMarker(Point.fromLngLat(mEndPoi.getLon(), mEndPoi.getLat()));

                                switchRouteLine(0);
                                if (routeCollection.size() > 0) {

                                    DirectionsRoute route = (DirectionsRoute) routeCollection.get(0).get(MainActivity.KEY_ROUTE_WHOLE);
                                    String dis = route.distance() + "米";
                                    if (route.distance() > 1000) {
                                        dis = StringUtils.formatDouble(route.distance() / 1000d, 1) + "公里";
                                    }
                                    SpannableString ss = new SpannableString("\n\n方案一\n\t" + dis + "\n\t");
                                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ff0000"));
                                    ss.setSpan(foregroundColorSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(1.5f);
                                    ss.setSpan(relativeSizeSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    mWay1.setText(ss);
                                    mWay1.setEnabled(true);
                                }

                                if (routeCollection.size() > 1) {
                                    DirectionsRoute route = (DirectionsRoute) routeCollection.get(1).get(MainActivity.KEY_ROUTE_WHOLE);
                                    String dis = route.distance() + "米";
                                    if (route.distance() > 1000) {
                                        dis = StringUtils.formatDouble(route.distance() / 1000d, 1) + "公里";
                                    }
                                    SpannableString ss = new SpannableString("\n\n方案二\n\t" + dis + "\n\t");
                                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ff0000"));
                                    ss.setSpan(foregroundColorSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(1.5f);
                                    ss.setSpan(relativeSizeSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                                    mWay2.setText(ss);
                                } else {
                                    mWay2.setText("");
                                    mWay2.setEnabled(false);
                                }

                                if (routeCollection.size() > 2) {
                                    DirectionsRoute route = (DirectionsRoute) routeCollection.get(2).get(MainActivity.KEY_ROUTE_WHOLE);
                                    String dis = route.distance() + "米";
                                    if (route.distance() > 1000) {
                                        dis = StringUtils.formatDouble(route.distance() / 1000d, 1) + "公里";
                                    }
                                    SpannableString ss = new SpannableString("\n\n方案三\n\t" + dis + "\n\t");
                                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#ff0000"));
                                    ss.setSpan(foregroundColorSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(1.5f);
                                    ss.setSpan(relativeSizeSpan, 5, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                                    mWay3.setText(ss);
                                } else {
                                    mWay3.setText("");
                                    mWay3.setEnabled(false);
                                }
                                boundCameraToRoute(route);
                                mGroupWays.setVisibility(View.VISIBLE);
                            }
                        });
                    } else {
                        Toast.makeText(getContext(), "距离太近，无法导航", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void switchRouteLine(int index) {
        List<DirectionsRoute> outRouteList = new ArrayList<>();
        List<DirectionsRoute> parkingtRouteCollect = new ArrayList<>();
        switch (index) {
            case 1:
                outRouteList.add((DirectionsRoute) (routeCollection.get(1)).get(MainActivity.KEY_ROUTE_OUT));
                outRouteList.add((DirectionsRoute) (routeCollection.get(0)).get(MainActivity.KEY_ROUTE_OUT));
                if (routeCollection.size() > 2) {
                    outRouteList.add((DirectionsRoute) (routeCollection.get(2)).get(MainActivity.KEY_ROUTE_OUT));
                }
                mWay1.setSelected(false);
                mWay2.setSelected(true);
                mWay3.setSelected(false);
                break;
            case 2:
                outRouteList.add((DirectionsRoute) (routeCollection.get(2)).get(MainActivity.KEY_ROUTE_OUT));
                outRouteList.add((DirectionsRoute) (routeCollection.get(0)).get(MainActivity.KEY_ROUTE_OUT));
                outRouteList.add((DirectionsRoute) (routeCollection.get(1)).get(MainActivity.KEY_ROUTE_OUT));
                mWay1.setSelected(false);
                mWay2.setSelected(false);
                mWay3.setSelected(true);
                break;
            default:
                mWay1.setSelected(true);
                mWay2.setSelected(false);
                mWay3.setSelected(false);
                // 收集所有的室外地图路径和停车场地图路径，因为目前停车场内部路径是一致的，所以使用第一个规划路径的停车场路径即可
                for (Map<String, Object> map : routeCollection) {
                    outRouteList.add((DirectionsRoute) map.get(MainActivity.KEY_ROUTE_OUT));
                }
                break;
        }
        parkingtRouteCollect.addAll((Collection<? extends DirectionsRoute>) routeCollection.get(0).get(MainActivity.KEY_ROUTE_PARKING));
        navigationMapboxMap.drawRoutes(outRouteList, parkingtRouteCollect);

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentView = inflater.inflate(R.layout.fragment_route_planning, null);

        mStartEdit = mFragmentView.findViewById(R.id.route_start);
        mEndEdit = mFragmentView.findViewById(R.id.route_end);

        mBackbtn = mFragmentView.findViewById(R.id.route_back);
        mBackbtn.setOnClickListener(this);

        mGroupType = mFragmentView.findViewById(R.id.route_style);
        mGroupSelect = mFragmentView.findViewById(R.id.route_select_poi_group);

        mRouteTypeCar = mFragmentView.findViewById(R.id.route_car);
        mRouteTypeCar.setOnClickListener(this);
        mRouteTypeCar.setSelected(true);

        mRouteTypeBike = mFragmentView.findViewById(R.id.route_bike);
        mRouteTypeBike.setOnClickListener(this);

        mRouteTypeWalk = mFragmentView.findViewById(R.id.route_walk);
        mRouteTypeWalk.setOnClickListener(this);

        mChangebtn = mFragmentView.findViewById(R.id.route_change);
        mChangebtn.setOnClickListener(this);

        mAvenueEdit1 = mFragmentView.findViewById(R.id.route_avenue_point1);
        mAvenueEdit2 = mFragmentView.findViewById(R.id.route_avenue_point2);
        mAvenueEdit3 = mFragmentView.findViewById(R.id.route_avenue_point3);

        mStartEdit.setOnFocusChangeListener(this);
        mEndEdit.setOnFocusChangeListener(this);
        mAvenueEdit1.setOnFocusChangeListener(this);
        mAvenueEdit2.setOnFocusChangeListener(this);
        mAvenueEdit3.setOnFocusChangeListener(this);

        mRouteSelectLoc = mFragmentView.findViewById(R.id.route_my_loc);
        mRouteSelectLoc.setOnClickListener(this);
        mRouteSelectMap = mFragmentView.findViewById(R.id.route_click_map);
        mRouteSelectMap.setOnClickListener(this);

        mRecommend = mFragmentView.findViewById(R.id.route_recommend);
        mRecommend.setOnClickListener(this);

        mNavi = mFragmentView.findViewById(R.id.route_simulation_navi);
        mNavi.setOnClickListener(this);

        mGroupWays = mFragmentView.findViewById(R.id.route_ways);
        mWay1 = mFragmentView.findViewById(R.id.route_way_1);
        mWay2 = mFragmentView.findViewById(R.id.route_way_2);
        mWay3 = mFragmentView.findViewById(R.id.route_way_3);
        mWay1.setOnClickListener(this);
        mWay2.setOnClickListener(this);
        mWay3.setOnClickListener(this);

        mClose1 = mFragmentView.findViewById(R.id.route_close1);
        mClose2 = mFragmentView.findViewById(R.id.route_close2);
        mClose3 = mFragmentView.findViewById(R.id.route_close3);

        mClose1.setOnClickListener(this);
        mClose2.setOnClickListener(this);
        mClose3.setOnClickListener(this);

        route_loc = mFragmentView.findViewById(R.id.route_loc);
        route_loc.setOnClickListener(this);

        mAdd = mFragmentView.findViewById(R.id.route_add);
        mAdd.setOnClickListener(this);

        mListView = mFragmentView.findViewById(R.id.route_search_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(layoutManager);
        mAdapter = new RoutePoiAutoAdapter();

        mListView.setAdapter(mAdapter);
        mAdapter.addOnItemClickListener(new RoutePoiAutoAdapter.OnItemClickListener() {
            @Override
            public void onShowPoi(Poi poi) {
                if (checkPoint(poi)) {
                    setPoi(poi);
                    getRoute();
                }
            }
        });
        mListView.setMoreListener(new ContentRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (mSelectEditText == null || TextUtils.isEmpty(mSelectEditText.getText()))
                    return;
                String key = mSelectEditText.getText().toString().trim();
                int count = mAdapter.getItemCount();
                if (mCallPoi == null && count % 10 == 0) {
                    int page = count / 10 + 1;
                    String url;
                    if (mCityCode != null)
                        url = UrlManager.getPoiSearchUrl(key, mCityCode, page, 10);
                    else
                        url = UrlManager.getPoiSearchUrl(key, page, 10);
                    mCallPoi = NetManager.getInstance().getData(url, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            mCallPoi = null;
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            mCallPoi = null;
                            final ArrayList<Poi> list = GsonManager.getInstance().parsePoiList(response.body().string());
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (list != null) {
                                        mAdapter.addData(list);
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });

        return mFragmentView;
    }

    private int currentFloor = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.route_back:
                FragmentsManager.getInstance().onBackPressed();
                break;
            case R.id.route_car:
                type = "car";
                if (!mRouteTypeCar.isSelected()) {
                    mRouteTypeCar.setSelected(true);
                    mRouteTypeWalk.setSelected(false);
                    mRouteTypeBike.setSelected(false);
                    getRoute();
                }
                break;
            case R.id.route_bike:
                type = "bike";
                if (!mRouteTypeBike.isSelected()) {
                    mRouteTypeCar.setSelected(false);
                    mRouteTypeWalk.setSelected(false);
                    mRouteTypeBike.setSelected(true);
                    getRoute();
                }
                break;
            case R.id.route_walk:
                type = "foot";
                if (!mRouteTypeWalk.isSelected()) {
                    mRouteTypeCar.setSelected(false);
                    mRouteTypeWalk.setSelected(true);
                    mRouteTypeBike.setSelected(false);
                    getRoute();
                }
                break;
            case R.id.route_change:
                Poi poiTemp = mStartPoi;
                mStartPoi = mEndPoi;
                mEndPoi = poiTemp;
                if (mStartPoi != null) {
                    mStartEdit.setText(mStartPoi.getName_zh());
                } else {
                    mStartEdit.setText("");
                }
                if (mEndPoi != null) {
                    mEndEdit.setText(mEndPoi.getName_zh());
                } else {
                    mEndEdit.setText("");
                }
                if (mStartPoi != null && mEndPoi != null) {
                    getRoute();
                }
                break;

            case R.id.route_my_loc:
                if (mSelectEditText != null && mSelectEditText.isFocusable()) {
                    Location location = MapManager.getInstance().getMapBox().getLocationComponent().getLastKnownLocation();
                    if (location == null) {
                        Toast.makeText(getContext(), "没有获取到当前位置", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Poi poi = new Poi();
                    poi.setLat(location.getLatitude());
                    poi.setLon(location.getLongitude());
                    poi.setName_zh("我的位置");
                    if (checkPoint(poi)) {
                        setPoi(poi);
                        getRoute();
                    }
                }
                break;
            case R.id.route_click_map:
                if (mListener != null && mListener instanceof OnRoutePanningFragmentListener) {
                    ((OnRoutePanningFragmentListener) mListener).onSelectPoiFromMap();
                }
                if (mSelectEditText != null) {
                    SystemUtil.hideKeyBoard(getActivity(), mSelectEditText);
                }
                break;
            case R.id.route_recommend:
                RecommendDialog dialog = new RecommendDialog(getActivity());
                dialog.setOnDialogListener(new RecommendDialog.OnRecommendDialogListener() {
                    @Override
                    public void onSelect(String name, int code) {
                        mRecommend.setText(name);
                        weighting = code;
                        getRoute();
                    }
                });
                dialog.show();
                break;
            case R.id.route_way_1:
                if (!mWay1.isSelected()) {
                    mWay1.setSelected(true);
                    mWay2.setSelected(false);
                    mWay3.setSelected(false);
                    switchRouteLine(0);
                }
                break;
            case R.id.route_way_2:
                if (!mWay2.isSelected()) {
                    mWay1.setSelected(false);
                    mWay2.setSelected(true);
                    mWay3.setSelected(false);
                    switchRouteLine(1);
                }
                break;
            case R.id.route_way_3:
                if (!mWay3.isSelected()) {
                    mWay1.setSelected(false);
                    mWay2.setSelected(false);
                    mWay3.setSelected(true);
                    switchRouteLine(2);
                }

                break;
            case R.id.route_add:
                if (mAvenueEdit1.getVisibility() != View.VISIBLE) {
                    mAvenueEdit1.setVisibility(View.VISIBLE);
                } else if (mAvenueEdit2.getVisibility() != View.VISIBLE) {
                    mAvenueEdit2.setVisibility(View.VISIBLE);
                } else if (mAvenueEdit3.getVisibility() != View.VISIBLE) {
                    mAvenueEdit3.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.route_close1:
                mAvenueEdit1.setText("");
                mAvenuePoi1 = null;
                mAvenueEdit1.setVisibility(View.GONE);
                break;
            case R.id.route_close2:
                mAvenueEdit2.setText("");
                mAvenuePoi2 = null;
                mAvenueEdit2.setVisibility(View.GONE);
                break;
            case R.id.route_close3:
                mAvenueEdit3.setText("");
                mAvenuePoi3 = null;
                mAvenueEdit3.setVisibility(View.GONE);
                break;
            case R.id.route_loc:
                MapManager.getInstance().jumpCurrentLoc();
                break;
            case R.id.route_simulation_navi:
                if (mListener != null && mListener instanceof OnRoutePanningFragmentListener) {
                    if (mWay1.isSelected())
                        ((OnRoutePanningFragmentListener) mListener).onShowRouteInfo(((DirectionsRoute) (routeCollection.get(0).get(MainActivity.KEY_ROUTE_WHOLE))), ((DirectionsRoute) (routeCollection.get(0).get(MainActivity.KEY_ROUTE_OUT))), ((List<DirectionsRoute>) (routeCollection.get(0).get(MainActivity.KEY_ROUTE_PARKING))));
                    else if(mWay2.isSelected())
                        ((OnRoutePanningFragmentListener) mListener).onShowRouteInfo(((DirectionsRoute) (routeCollection.get(1).get(MainActivity.KEY_ROUTE_WHOLE))), ((DirectionsRoute) (routeCollection.get(1).get(MainActivity.KEY_ROUTE_OUT))), ((List<DirectionsRoute>) (routeCollection.get(1).get(MainActivity.KEY_ROUTE_PARKING))));
                    else if(mWay3.isSelected())
                        ((OnRoutePanningFragmentListener) mListener).onShowRouteInfo(((DirectionsRoute) (routeCollection.get(2).get(MainActivity.KEY_ROUTE_WHOLE))), ((DirectionsRoute) (routeCollection.get(2).get(MainActivity.KEY_ROUTE_OUT))), ((List<DirectionsRoute>) (routeCollection.get(2).get(MainActivity.KEY_ROUTE_PARKING))));
                }
                break;
        }
    }

    @Override
    public void onHideOrRemove(boolean bRemove) {
        super.onHideOrRemove(bRemove);
        if (bRemove) {
            navigationMapboxMap.clearMarkers();
            navigationMapboxMap.removeRoute();
        }
        if (mCallPoi != null && mCallPoi.isExecuted()) {
            mCallPoi.cancel();
        }
        if (mCallRoute != null && mCallRoute.isExecuted()) {
            mCallRoute.cancel();
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            mGroupType.setVisibility(View.GONE);
            mGroupWays.setVisibility(View.GONE);
            mGroupSelect.setVisibility(View.VISIBLE);
            mSelectEditText = (EditText) v;
            mSelectEditText.addTextChangedListener(this);
        } else {
            mGroupType.setVisibility(View.VISIBLE);
            mGroupSelect.setVisibility(View.GONE);
            mListView.setVisibility(View.GONE);
            mSelectEditText.removeTextChangedListener(this);
        }
    }

    private boolean checkPoint(Poi poi) {
        if (mStartPoi != null) {
            if (!checkPoint(mStartPoi, poi)) {
                return false;
            }
        }
        if (mEndPoi != null) {
            if (!checkPoint(mEndPoi, poi)) {
                return false;
            }
        }
        if (mAvenuePoi1 != null) {
            if (!checkPoint(mAvenuePoi1, poi)) {
                return false;
            }
        }
        if (mAvenuePoi2 != null) {
            if (!checkPoint(mAvenuePoi2, poi)) {
                return false;
            }
        }
        if (mAvenuePoi3 != null) {
            if (!checkPoint(mAvenuePoi3, poi)) {
                return false;
            }
        }
        return true;
    }

    private boolean checkPoint(Poi poi1, Poi poi2) {
        if (poi1 == null || poi2 == null)
            return false;
        if (poi1.getName_zh().equals(poi2.getName_zh()) && poi1.getName_zh().equals("我的位置")) {
            Toast.makeText(getContext(), "我的位置已存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (poi1.getLat() == poi2.getLat() && poi1.getLon() == poi2.getLon()) {
            Toast.makeText(getContext(), "已存在相同的点", Toast.LENGTH_SHORT).show();
            return false;
        }

        double dis = PositionUtil.getDistance(poi1.getLon(), poi1.getLat(), poi2.getLon(), poi2.getLat());
        if (dis < 10) {
            Toast.makeText(getContext(), "距离过近", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void setPoi(Poi poi) {
        if (mSelectEditText != null) {
            mSelectEditText.clearFocus();
            mSelectEditText.setText(poi.getName_zh());
            SystemUtil.hideKeyBoard(getActivity(), mSelectEditText);
            if (mSelectEditText == mStartEdit) {
                mStartPoi = poi;
            } else if (mSelectEditText == mEndEdit) {
                mEndPoi = poi;
            } else if (mAvenueEdit1 == mSelectEditText) {
                mAvenuePoi1 = poi;
            } else if (mAvenueEdit2 == mSelectEditText) {
                mAvenuePoi2 = poi;
            } else if (mAvenueEdit3 == mSelectEditText) {
                mAvenuePoi3 = poi;
            }
        }
        if (mAvenuePoi1 != null) {
            wayPoints.add(Point.fromLngLat(mAvenuePoi1.getLon(), mAvenuePoi1.getLat()));
        }
        if (mAvenuePoi2 != null) {
            wayPoints.add(Point.fromLngLat(mAvenuePoi2.getLon(), mAvenuePoi2.getLat()));
        }
        if (mAvenuePoi3 != null) {
            wayPoints.add(Point.fromLngLat(mAvenuePoi3.getLon(), mAvenuePoi3.getLat()));
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (mSelectEditText != null && mSelectEditText.isFocusable()) {
            if (s.length() != 0 && s.toString().trim().length() != 0) {
                if (mHandler.hasMessages(handler_PoiAuto)) {
                    mHandler.removeMessages(handler_PoiAuto);
                }
                Message msg = Message.obtain();
                msg.what = handler_PoiAuto;
                msg.obj = s.toString(); //携带当前值
                mHandler.sendMessageDelayed(msg, 500);

            } else {
                if (mHandler.hasMessages(handler_PoiAuto)) {
                    mHandler.removeMessages(handler_PoiAuto);
                }
            }
        }
    }

    private static final int CAMERA_ANIMATION_DURATION = 1000; // 动画时间

    public void boundCameraToRoute(DirectionsRoute route) {
        if (route != null) {
            List<Point> routeCoords = LineString.fromPolyline(route.geometry(),
                    6).coordinates();
            List<LatLng> bboxPoints = new ArrayList<>();
            for (Point point : routeCoords) {
                bboxPoints.add(new LatLng(point.latitude(), point.longitude()));
            }
            if (bboxPoints.size() > 1) {
                try {
                    LatLngBounds bounds = new LatLngBounds.Builder().includes(bboxPoints).build();
                    // left, top, right, bottom
                    animateCameraBbox(bounds, CAMERA_ANIMATION_DURATION, new int[]{50, 100, 50, 100});
                } catch (InvalidLatLngBoundsException exception) {
                    Toast.makeText(getActivity(), "无法定位路径位置", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void animateCameraBbox(LatLngBounds bounds, int animationTime, int[] padding) {
        CameraPosition position = navigationMapboxMap.retrieveMap().getCameraForLatLngBounds(bounds, padding);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(position);
        NavigationCameraUpdate navigationCameraUpdate = new NavigationCameraUpdate(cameraUpdate);
        navigationCameraUpdate.setMode(CameraUpdateMode.OVERRIDE);
        navigationMapboxMap.retrieveCamera().update(navigationCameraUpdate, animationTime);
    }

    private void connectRouteLegs(DirectionsRoute route) {
        if (route != null && route.legs() != null) {
            for (RouteLeg leg : route.legs()) {
                if (leg.steps() != null && !leg.steps().isEmpty()) {
//                    Point lastPoint=Point.fromLngLat(0,0);
//                    Iterator iterator=leg.steps().iterator();
//                    while (iterator.hasNext()){
//                        LegStep legStep= (LegStep) iterator.next();
//                        List<Point> pointList=PolylineUtils.decode(legStep.geometry(), 6);
//                        iterator.remove();
//                    }
//                    Map<Integer, LegStep> map = new HashMap<>();
                    Iterator iterator = leg.steps().iterator();
                    while (iterator.hasNext()) {
                        LegStep legStep = (LegStep) iterator.next();
                        List<Point> pointList = PolylineUtils.decode(legStep.geometry(), 6);
                        if (pointList != null && !pointList.isEmpty() && pointList.size() == 2) {
//                            if (lastPoint.longitude()!=0&&lastPoint.latitude()!=0&&lastPoint.longitude()!=pointList.get(0).longitude()&&lastPoint.latitude()!=pointList.get(0).latitude()){
////                                pointList.add(0,lastPoint);
////                                legStep=legStep.toBuilder().geometry(PolylineUtils.encode(pointList, 6)).build();
////                                map.put(i, legStep);
//                            }
//                            lastPoint = Point.fromLngLat(pointList.get(pointList.size()-1).longitude(),pointList.get(pointList.size()-1).latitude());
                            if (pointList.get(0).latitude() == pointList.get(1).latitude() && pointList.get(0).longitude() == pointList.get(1).longitude() && iterator.hasNext()/*说明当前路径不是最后一个终点路径*/) {
                                iterator.remove();
                            }
                        }
                    }
//                    if (!map.isEmpty()){
//                        for (Integer key:map.keySet()){
//                            leg.steps().remove(key);
//                            leg.steps().add(key,map.get(key));
//                        }
//                    }
                }
            }
        }
    }
}
